//
//  XFImagePickerAssetsController.swift
//  multi_show
//
//  Created by 李旭峰 on 2020/9/15.
//

import UIKit
import AssetsLibrary
import CoreImage
import Foundation
import Photos

class XFImagePickerAssetsController: UIViewController,UICollectionViewDataSource,UICollectionViewDelegate {
    weak var delegate:MTImagePickerDataSourceDelegate!
    var groupModel:MTImagePickerAlbumModel!
    
    private lazy var collectionView: XFImagePickerCollectionView = {
        let config = MTImagePickerFlowLayout()
        let collectionView = XFImagePickerCollectionView(frame: CGRect.zero, collectionViewLayout: config)
        collectionView.delegate = self
        collectionView.dataSource = self
        return collectionView
    }()
    private lazy var lbSelected: UILabel = UILabel()
    private lazy var btnPreview: UIButton = UIButton(type: .custom)
    
    private var dataSource = [MTImagePickerModel]()
    private var initialScrollDone:Bool = false
    
    class var instance:XFImagePickerAssetsController {
        get {
            return XFImagePickerAssetsController()
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        self.collectionView.backgroundColor = UIColor.white
        let vSaveTopView = UIView()
        self.view.addSubview(vSaveTopView)
        vSaveTopView.snp.makeConstraints { (make) in
            make.leading.top.trailing.equalToSuperview()
            make.height.equalTo(vSafeTop)
        }
        let headerView = UIView()
        self.view.addSubview(headerView)
        headerView.snp.makeConstraints { (make) in
            make.leading.trailing.equalToSuperview()
            make.top.equalTo(vSaveTopView.snp.bottom)
            make.height.equalTo(44)
        }
        let btnCancel = UIButton(type: .custom)
        btnCancel.setTitle("Cancel", for: .normal)
        btnCancel.setTitleColor(UIColor(hexStr: "#047AFF", alpha: 1.0), for: .normal)
        btnCancel.titleLabel?.font = FontAsset.PingFangSC_Regular.size(14)
        btnCancel.addTarget(self, action: #selector(btnCancelTouch(_:)), for: .touchUpInside)
        headerView.addSubview(btnCancel)
        btnCancel.snp.makeConstraints { (make) in
            make.top.trailing.bottom.equalToSuperview()
            make.width.equalTo(80)
        }
        self.view.addSubview(self.collectionView)
        self.collectionView.snp.makeConstraints { (make) in
            make.leading.trailing.equalToSuperview()
            make.top.equalTo(headerView.snp.bottom)
        }
        let bottomView = UIView()
        self.view.addSubview(bottomView)
        bottomView.addSubview(self.btnPreview)
        bottomView.snp.makeConstraints { (make) in
            make.leading.trailing.equalToSuperview()
            make.top.equalTo(self.collectionView.snp.bottom)
            make.height.equalTo(44)
        }
        self.btnPreview.setTitle("Preview", for: .normal)
        self.btnPreview.titleLabel?.font = FontAsset.PingFangSC_Regular.size(12)
        self.btnPreview.setTitleColor(UIColor(hexStr: "#047AFF", alpha: 1.0), for: .normal)
        self.btnPreview.addTarget(self, action: #selector(btnPreviewTouch(_:)), for: .touchUpInside)
        self.btnPreview.snp.makeConstraints { (make) in
            make.top.leading.bottom.equalToSuperview()
            make.width.equalTo(80)
        }
        self.lbSelected.text = "0"
        self.lbSelected.textAlignment = .center
        self.lbSelected.textColor = UIColor.white
        self.lbSelected.font = FontAsset.PingFangSC_Medium.size(14)
        self.lbSelected.layer.cornerRadius = 10
        self.lbSelected.layer.masksToBounds = true
        self.lbSelected.backgroundColor = UIColor(hexStr: "#047AFF", alpha: 1.0)
        bottomView.addSubview(self.lbSelected)
        self.lbSelected.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.height.equalTo(20)
            make.width.equalTo(40)
        }
        let btnDone = UIButton(type: .custom)
        btnDone.setTitle("Done", for: .normal)
        btnDone.setTitleColor(UIColor(hexStr: "#047AFF", alpha: 1.0), for: .normal)
        btnDone.titleLabel?.font = FontAsset.PingFangSC_Regular.size(14)
        btnDone.addTarget(self, action: #selector(btnFinishTouch(_:)), for: .touchUpInside)
        bottomView.addSubview(btnDone)
        btnDone.snp.makeConstraints { (make) in
            make.top.trailing.bottom.equalToSuperview()
            make.width.equalTo(80)
            make.leading.equalTo(self.lbSelected.snp.trailing)
        }
        let vSaveBottomView = UIView()
        self.view.addSubview(vSaveBottomView)
        vSaveBottomView.snp.makeConstraints { (make) in
            make.top.equalTo(bottomView.snp.bottom)
            make.leading.trailing.bottom.equalToSuperview()
            make.height.equalTo(vSafeBottom)
        }
        
        self.collectionView.register(XFImagePickerCell.self, forCellWithReuseIdentifier: "XFImagePickerCell")
//        if let title = self.groupModel?.getAlbumName() {
//            self.title = title
//        }
//        let loading = LoadingViewController()
//        loading.show(text: "正在加载...")
        self.groupModel?.getMTImagePickerModelsListAsync {[weak self] (models) in
            guard let `self` = self else { return }
//            loading.dismiss()
            self.dataSource = models
            self.collectionView.reloadData()
            self.scrollToBottom()
        }
    }

    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: false)
        self.collectionView.reloadData()
        self.lbSelected.text = String(delegate.selectedSource.count)
        self.btnPreview.isEnabled = !(delegate.selectedSource.count == 0)
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        if !self.initialScrollDone {
            self.initialScrollDone = true
            self.scrollToBottom()
        }
    }
    
    //MARK: UICollectionViewDelegate
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.dataSource.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: "XFImagePickerCell", for: indexPath) as! XFImagePickerCell
        cell.contentView.backgroundColor = UIColor.white
        let model = self.dataSource[indexPath.row]
        if model.mediaType == .Video   {
            cell.videoView.isHidden = false
            model.getVideoDurationAsync(){
                duration in
                DispatchQueue.main.async {
                    cell.videoDuration.text = duration.timeFormat()

                }
            }
        } else {
            cell.videoView.isHidden = true
        }
        cell.imageView.image = model.getThumbImage(size: cell.imageView.frame.size)
        cell.indexPath = indexPath
        cell.btnCheck.isSelected = delegate.selectedSource.contains(model)
        cell.btnCheck.addTarget(self, action: #selector(XFImagePickerAssetsController.btnCheckTouch(_:)), for: .touchUpInside)
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        self.pushToImageSelectorPreviewController(initialIndexPath: indexPath, dataSource: self.dataSource)
        
    }
    
    @objc func btnCheckTouch(_ sender:UIButton) {
        if delegate.selectedSource.count < delegate.maxCount || sender.isSelected == true {
            sender.isSelected = !sender.isSelected
            let index = (sender.superview?.superview as! XFImagePickerCell).indexPath.row
            if sender.isSelected {
               delegate.selectedSource.append(self.dataSource[index])
                sender.heartbeatsAnimation(duration: 0.15)
            }else {
                if let removeIndex = delegate.selectedSource.index(of: self.dataSource[index]) {
                    delegate.selectedSource.remove(at: removeIndex)
                }
            }
            self.lbSelected.text = String(delegate.selectedSource.count)
            self.lbSelected.heartbeatsAnimation(duration: 0.15)
            self.btnPreview.isEnabled = !(delegate.selectedSource.count == 0)
        } else {
            let alertView = FlashAlertView(message: "已达到最大选择数", delegate: nil)
            alertView.show()
        }
    }
    
    //旋转处理
    override func willRotate(to toInterfaceOrientation: UIInterfaceOrientation, duration: TimeInterval) {
        if self.interfaceOrientation.isPortrait != toInterfaceOrientation.isPortrait {
            self.collectionView.prevItemSize = (self.collectionView.collectionViewLayout as! MTImagePickerFlowLayout).itemSize
            self.collectionView.prevOffset = self.collectionView.contentOffset.y
            self.collectionView.collectionViewLayout.invalidateLayout()
        }
    }
    
    //MARK: private methods
    
    private func scrollToBottom() {
        if self.dataSource.count > 0 {
            let indexPath = IndexPath(row: self.dataSource.count - 1 , section: 0)
            self.collectionView.scrollToItem(at: indexPath, at:.bottom, animated: false)
        }
    }
    
    private func pushToImageSelectorPreviewController(initialIndexPath:IndexPath?,dataSource:[MTImagePickerModel]) {
        let vc = XFImagePickerPreviewController()
        vc.dataSource = dataSource
        vc.delegate = self.delegate
        vc.initialIndexPath = initialIndexPath
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    //MARK: IBActions
    @IBAction func btnFinishTouch(_ sender: AnyObject) {
        delegate.didFinishPicking()
    }
    
    @IBAction func btnPreviewTouch(_ sender: AnyObject) {
        let dataSource = delegate.selectedSource
        self.pushToImageSelectorPreviewController(initialIndexPath: nil, dataSource: dataSource)
    }
    @IBAction func btnCancelTouch(_ sender: AnyObject) {
        delegate.didCancel()
    }
}


class XFImagePickerCollectionView:UICollectionView {
    var prevItemSize:CGSize?
    var prevOffset:CGFloat = 0
}
